import Vue from "vue";
// import { executePreditct } from "@/api/tenant";
import { Bus } from "@/utils/bus";

export function getConditionValBol(condition, valArray) {
  // 为空,有值,没值,为真,为假 是没有valArray输入
  const excepCondition = ["is", "exists", "not exists"];
  const conditionValBol =
    (!excepCondition.includes(condition) && valArray.length === 0) ||
    valArray.includes(undefined) ||
    valArray.includes(null);
  return conditionValBol;
}
/**
 * 获取ruleJson的v值
 * 操作符等于为空时，删除v值
 * @param {array} valArray
 * @param {string} condition
 */
export function getVObj(valArray, condition) {
  const vObj = {
    v: valArray.length > 0 ? valArray.join(",") : "",
  };
  if (condition === "is") {
    delete vObj.v;
  }
  return vObj;
}
/**
 * input输入框,type = 'input_single'
 * 用于 <!-- 时间-在xx天之前/之内 -->
 * 目标：将非数字设置为0
 * @param {string||number} val 输入框输入的值
 * @param {number} index valArray数组的索引
 * @param {array} valArray 属性值数组
 */
export function intNumChange(val, index, valArray) {
  const n = Number(val);
  if (isNaN(n) || val === undefined || val === null) {
    Vue.set(valArray, index, 1);
  }
}

/**
 * input输入框，type="between"
 * 用于数值类型的操作符为区间
 * input输入框，type = "input_between"
 * 用于日期类型 在（过去||未来）XX天至（过去||未来）XX天之内
 * @param {string||number} val 输入框输入的值
 * @param {number} index valArray数组的索引
 * @param {array} valArray 属性值数组
 * @param {array} proper 选择属性的数组
 */
export function dateBetweenChange(val, index, valArray, proper) {
  Bus.$emit("memberChange");
  const [val0, val1] = valArray;
  const property =
    proper.length > 0 ? proper[proper.length - 1].split("#") : [];
  if (property.includes("relative_pass_between")) {
    if (val0 < val1) {
      Vue.set(valArray, 0, val1);
      Vue.set(valArray, 1, val0);
    }
  } else {
    // 在未来XX天至未来XX天之内||数值区间，前面数字必须小于后面数字
    if (val0 > val1) {
      Vue.set(valArray, 0, val1);
      Vue.set(valArray, 1, val0);
    }
  }
}

/**
 * 下拉框 type="number||enum"
 * 用于数值类型和枚举类型的下拉框
 * 通过multiple判断下拉框是否可以手动输入，enum不可手动输入
 * @param {string||number} val 输入框输入的值
 * @param {array} valArray 属性值数组
 * @param {*} multiple 操作符列表
 */
export function inputChange(val, valArray, multiple) {
  Bus.$emit("memberChange");
  if (multiple && multiple.length > 0) {
    // 正常下拉多选,multiple.length>0 代表el-select为enum模式
    return val;
  }
  const value = val[val.length - 1];
  var n = Number(value);
  if (isNaN(n)) {
    valArray.splice(valArray.length - 1, 1);
  }
}

export const tagMixin = {
  data() {
    return {
      moduleCount: "", // 群组-全部-计算人数
      moduleLoading: false, // 群组-全部-loading
    };
  },
  methods: {
    /**
     * 获取用户属性满足-选择标签或者群组时的code
     * @param {array} tagList 群组/标签列表
     */
    getUserTagGroupCode(tagList) {
      const userTagCodesArr = []; // 用户标签code集合
      const userGroupCodesArr = []; // 用户群组code集合
      for (let i = 0; i < tagList.length; i++) {
        const { propertyArr } = tagList[i];
        for (let j = 0; j < propertyArr.length; j++) {
          const { attrChildArr } = propertyArr[j];
          attrChildArr.forEach(({ property }) => {
            if (property.includes("user_tag_group_header")) {
              userTagCodesArr.push(property[property.length - 1]);
            }
            if (property.includes("user_group_header")) {
              userGroupCodesArr.push(property[property.length - 1]);
            }
          });
        }
      }
      const userTagCodes = userTagCodesArr.join(",");
      const userGroupCodes = userGroupCodesArr.join(",");
      return { userTagCodes, userGroupCodes };
    },
    /**
     * 用于验证用户属性满足是否满足条件
     * @param {array} propertyArr
     */
    validateUserFn(propertyArr) {
      for (let j = 0; j < propertyArr.length; j++) {
        const { attrChildArr } = propertyArr[j];
        for (let n = 0; n < attrChildArr.length; n++) {
          const { property, valArray, condition } = attrChildArr[n];
          if (property.length === 0) {
            return { code: "error", msg: `用户属性不能为空` };
          }
          const conditionValBol = getConditionValBol(condition, valArray);
          if (conditionValBol) {
            return { code: "error", msg: `用户属性值不能为空` };
          }
        }
      }
      return { code: "ok" };
    },
    /**
     * 用于验证交易满足是否满足条件
     * @param {array} behaviourArr
     */
    validateBehaviourFn(behaviourArr) {
      for (let j = 0; j < behaviourArr.length; j++) {
        const { attrChildArr } = behaviourArr[j];
        for (let n = 0; n < attrChildArr.length; n++) {
          const { property, condition, valArray, screenArr } = attrChildArr[n];
          if (property.length === 0) {
            return { code: "error", msg: `交易行为属性不能为空` };
          }
          // 为空,有值,没值,为真,为假 是没有valArray输入
          const conditionValBol = getConditionValBol(condition, valArray);
          if (conditionValBol) {
            return { code: "error", msg: `交易行为属性值不能为空` };
          }
          if (screenArr.length > 0) {
            for (let m = 0; m < screenArr.length; m++) {
              const { property, condition, valArray } = screenArr[m];
              if (property.length === 0) {
                return { code: "error", msg: `交易行为筛选条件属性不能为空` };
              }
              const conditionValBol = getConditionValBol(condition, valArray);
              if (conditionValBol) {
                return { code: "error", msg: `交易行为筛选条件属性值不能为空` };
              }
            }
          }
        }
      }
      return { code: "ok" };
    },
    /**
     * 获取用户属性满足的规则引擎表达式
     * @param {object} tagListItem
     */
    getUserExpress(tagListItem) {
      const { propertyArr, propertyAndOr } = tagListItem;
      const userObject = {
        logic: propertyAndOr === "1" ? "AND" : "OR",
        express: [],
      };
      const userExpress = [];
      if (propertyArr.length === 0) return userExpress;
      for (let j = 0; j < propertyArr.length; j++) {
        const { childAndOr, attrChildArr } = propertyArr[j];
        const propertyObj = {
          logic: childAndOr === "1" ? "AND" : "OR",
          express: [],
        };
        for (let n = 0; n < attrChildArr.length; n++) {
          const { valArray, property, condition } = attrChildArr[n];
          const vObj = getVObj(valArray, condition);
          const attrObj = {
            code: property[property.length - 1],
            op: condition,
            ...vObj,
          };
          propertyObj.express.push(attrObj);
        }
        userObject.express.push(propertyObj);
      }
      userExpress.push(userObject);
      return userExpress;
    },
    /**
     * 获取交易行为满足的规则引擎表达式
     * @param {object} tagListItem
     */
    getBehaviourExpress(tagListItem) {
      const behaviourExpress = [];
      const { behaviourArr = [], behaviourAndOr } = tagListItem;
      const behaviourObject = {
        logic: behaviourAndOr === "1" ? "AND" : "OR",
        express: [],
      };
      if (behaviourArr.length === 0) return behaviourExpress;
      for (let j = 0; j < behaviourArr.length; j++) {
        const { childAndOr, attrChildArr } = behaviourArr[j];
        const behaviourObj = {
          logic: childAndOr === "1" ? "AND" : "OR",
          express: [],
        };
        for (let n = 0; n < attrChildArr.length; n++) {
          const {
            property,
            valArray,
            condition,
            childAndOr,
            screenArr,
          } = attrChildArr[n];
          const vObj = getVObj(valArray, condition);
          const attrObj = {
            code: property[property.length - 1],
            op: condition,
            ...vObj,
          };
          if (screenArr.length > 0) {
            const screenArrObj = {
              logic: childAndOr === "1" ? "AND" : "OR",
              express: [],
            };
            for (let m = 0; m < screenArr.length; m++) {
              const { property, valArray, condition } = screenArr[m];
              const vObj = getVObj(valArray, condition);
              const screenObj = {
                code: property[property.length - 1],
                op: condition,
                ...vObj,
              };
              screenArrObj.express.push(screenObj);
            }
            behaviourObj.express.push(screenArrObj);
          }
          behaviourObj.express.push(attrObj);
        }
        behaviourObject.express.push(behaviourObj);
      }
      behaviourExpress.push(behaviourObject);
      return behaviourExpress;
    },
    /**
     * 获取群组&&标签rulejson
     * @param {array} tagList 群组列表
     * @param {string} type 根据type,确定name是传中文名称还是传index
     */
    getCustomizeExpress(tagList, type = "default") {
      const customizeExpress = [];
      for (let i = 0; i < tagList.length; i++) {
        const userExpress = this.getUserExpress(tagList[i]);
        const behaviourExpress = this.getBehaviourExpress(tagList[i]);
        const modelExpress = this.getModelExpress(tagList[i]);
        const { name, description } = tagList[i];
        let tagObj = {};
        if (name && type === "default") {
          tagObj = { name, description };
        } else {
          tagObj = { name: i, description };
        }
        const customizeObj = {
          ...tagObj,
          expressObj: {
            logic: tagList[i].childAndOr === "1" ? "AND" : "OR",
            express: [],
          },
        };
        customizeObj.expressObj.express = [
          ...userExpress,
          ...behaviourExpress,
          ...modelExpress,
        ];
        customizeExpress.push(customizeObj);
      }
      return customizeExpress;
    },
    /**
     * 标签方法集合
     * @param {array} tagList
     */
    /**
     * 获取标签分层名称
     * @param {array} tagList 标签列表
     */
    getTagLayerName(tagList) {
      const layerName = tagList.map(({ name }) => {
        return {
          name,
          code: `${name}`,
        };
      });
      return layerName;
    },
    validateTagFun(tagList) {
      for (let i = 0; i < tagList.length; i++) {
        const { propertyArr, behaviourArr, name, errMsg } = tagList[i];
        if (!name) {
          return { code: "error", msg: `分层名称不能为空` };
        }
        if (errMsg) {
          return { code: "error", msg: `分层名称不可重复` };
        }
        if (propertyArr.length === 0 && behaviourArr.length === 0) {
          return { code: "error", msg: `${name}:请添加有效规则` };
        }
        const validateUserRes = this.validateUserFn(propertyArr);
        if (validateUserRes.code === "error") {
          return validateUserRes;
        }
        const validateBehaviourRes = this.validateBehaviourFn(behaviourArr);
        if (validateBehaviourRes.code === "error") {
          return validateBehaviourRes;
        }
      }
      return { code: "ok" };
    },
    /**
     * 群组方法集合
     * @param {array} tagList
     */
    /**
     *  countFn用于群组计算
     *  @param {number} val 群组模块
     *   val === "property" 用户属性满足
     *   val === 'behaviour' 交易行为满足
     *   val === 'model' 模型筛选
     *   val === 'module' 整个模块计算
     */
    async countFn(slotData) {
      const { type } = slotData;
      const tagList = this.tagList;
      let customizeExpress = [];
      let groupRuleJson = "";
      let validateRes = {};
      const { propertyArr, modelArr, behaviourArr } = tagList[0];
      if (type === "property") {
        if (propertyArr.length === 0) {
          this.$message.error("请添加有效规则");
          return;
        }
        this.$set(slotData, "calcLoading", true);
        validateRes = this.validateUserFn(propertyArr);
        if (validateRes.code === "error") {
          this.$message.error(validateRes.msg);
          return;
        }
        for (let i = 0; i < tagList.length; i++) {
          const userExpress = this.getUserExpress(tagList[i]);
          const customizeObj = {
            expressObj: {
              logic: tagList[i].childAndOr === "1" ? "AND" : "OR",
              express: [],
            },
          };
          customizeObj.expressObj.express = [...userExpress];
          customizeExpress.push(customizeObj);
        }
      } else if (type === "behaviour") {
        if (behaviourArr.length === 0) {
          this.$message.error("请添加有效规则");
          return;
        }
        this.$set(slotData, "calcLoading", true);
        validateRes = this.validateBehaviourFn(behaviourArr);
        if (validateRes.code === "error") {
          this.$message.error(validateRes.msg);
          return;
        }
        for (let i = 0; i < tagList.length; i++) {
          const behaviourExpress = this.getBehaviourExpress(tagList[i]);
          const customizeObj = {
            expressObj: {
              logic: tagList[i].childAndOr === "1" ? "AND" : "OR",
              express: [],
            },
          };
          customizeObj.expressObj.express = [...behaviourExpress];
          customizeExpress.push(customizeObj);
        }
      } else if (type === "model") {
        if (modelArr.length === 0) {
          this.$message.error("请添加有效规则");
          return;
        }
        this.$set(slotData, "calcLoading", true);
        validateRes = this.validateModelFn(modelArr);
        if (validateRes.code === "error") {
          this.$message.error(validateRes.msg);
          return;
        }
        for (let i = 0; i < tagList.length; i++) {
          const customizeObj = {
            expressObj: {
              logic: tagList[i].childAndOr === "1" ? "AND" : "OR",
              express: [],
            },
          };
          const modelExpress = this.getModelExpress(tagList[i]);
          customizeObj.expressObj.express = [...modelExpress];
          customizeExpress.push(customizeObj);
        }
      } else {
        const validateRes = this.validateGroupFun(tagList);
        if (validateRes.code === "error") {
          this.$message.error(validateRes.msg);
          return;
        }
        this.moduleLoading = true;
        customizeExpress = this.getCustomizeExpress(tagList);
      }
      groupRuleJson = JSON.stringify(customizeExpress[0]);
      const params = {
        ruleJson: groupRuleJson,
      };
      console.log(params);
      // const { code, data: count } = await executePreditct(params);
      // if (code === 0) {
      //   if (type === "module") {
      //     this.moduleCount = count;
      //     this.moduleLoading = false;
      //     return;
      //   }
      //   this.$set(slotData, "calcLoading", false);
      //   this.$set(slotData, "calcCount", count);
      // }
    },
    /**
     * 用于验证模型筛选是否满足条件
     * @param {array} modelArr
     */
    validateModelFn(modelArr) {
      for (let j = 0; j < modelArr.length; j++) {
        const { attrChildArr } = modelArr[j];
        for (let n = 0; n < attrChildArr.length; n++) {
          const { property, condition, valArray } = attrChildArr[n];
          if (property.length === 0) {
            return { code: "error", msg: `模型属性不能为空` };
          }
          const conditionValBol = getConditionValBol(condition, valArray);
          if (conditionValBol) {
            return { code: "error", msg: `模型属性值不能为空` };
          }
        }
      }
      return { code: "ok" };
    },
    /**
     * 用于验证用户群组满足/交易行为满足/模型筛选是否满足条件
     * @param {array} modelArr
     */
    validateGroupFun(tagList) {
      for (let i = 0; i < tagList.length; i++) {
        const { propertyArr, modelArr, behaviourArr } = tagList[i];
        if (
          modelArr.length === 0 &&
          propertyArr.length === 0 &&
          behaviourArr.length === 0
        ) {
          return { code: "error", msg: `请添加有效规则` };
        }
        const validateUserRes = this.validateUserFn(propertyArr);
        if (validateUserRes.code === "error") {
          return validateUserRes;
        }
        const validateBehaviourRes = this.validateBehaviourFn(behaviourArr);
        if (validateBehaviourRes.code === "error") {
          return validateBehaviourRes;
        }
        const validateModelRes = this.validateModelFn(modelArr);
        if (validateModelRes.code === "error") {
          return validateModelRes;
        }
      }
      return { code: "ok" };
    },
    /**
     * 用于设置群组来源
     * 群组来源:0:交叉筛选;1:受众上传;2:受众交并;3:标签筛选;4:行为筛选;5:模型筛选
     * 交叉筛选条件：模型筛选存在条件并且用户属性满足和交易行为满足最少满足一个存在条件值
     * 标签筛选条件：模型筛选不存在条件值，用户属性满足和交易行为满足最少满足一个存在条件值
     * 模型筛选条件：模型筛选存在条件值，用户属性满足和交易行为满足都不存在条件值
     * @param {array} tagList
     */
    getGroupSource(tagList) {
      let groupSource = "";
      const { behaviourArr, propertyArr, modelArr } = tagList[0];
      if (behaviourArr.length || propertyArr.length) {
        if (modelArr.length) {
          groupSource = 0;
        } else {
          groupSource = 3;
        }
      } else if (behaviourArr.length === 0 && propertyArr.length === 0) {
        groupSource = 5;
      }
      return groupSource;
    },
    /**
     * 获取模型筛选的规则引擎表达式
     * @param {object} tagListItem
     */
    getModelExpress(tagListItem) {
      const modelExpress = [];
      const { modelArr = [], modelAndOr } = tagListItem;
      const modelObject = {
        logic: modelAndOr === "1" ? "AND" : "OR",
        express: [],
      };
      if (modelArr.length === 0) return modelArr;
      for (let j = 0; j < modelArr.length; j++) {
        const { childAndOr, attrChildArr } = modelArr[j];
        const modelObj = {
          logic: childAndOr === "1" ? "AND" : "OR",
          express: [],
        };
        for (let n = 0; n < attrChildArr.length; n++) {
          const { valArray, condition, property } = attrChildArr[n];
          const vObj = getVObj(valArray, condition);
          const attrObj = {
            code: property[property.length - 1],
            op: condition,
            ...vObj,
          };
          modelObj.express.push(attrObj);
        }
        modelObject.express.push(modelObj);
      }
      modelExpress.push(modelObject);
      return modelExpress;
    },
  },
};
